<template>
    <div class="files">
        <div v-if="count > 0" class="files_tool">

            <yk-space>
                <yk-checkbox :checked="checkedAll" :indeterminate="indeterminate"
                    @change="handleChangeAll">全选</yk-checkbox>
                <yk-text>已选择 {{ checkedId.length }} 项内容</yk-text>
                <yk-text type="primary" style="cursor: pointer;" @click="uncheck"
                    v-show="checkedId.length">取消选择</yk-text>

            </yk-space>
            <yk-space v-show="checkedId.length">
                <IconDeleteOutline class="files_tool-delete" @click="filesDelete" />
                <yk-popconfirm title="选择分组" placement="bottomRight" trigger="click" :arrow="false" @cancel="cancel"
                    @confirm="confirm">
                    <IconSwitchOutline class="file_tool-switch" />
                    <template #content>
                        <yk-scrollbar ref="scrollbar" height="148px" class="subset">
                            <div v-for="item in subsetStore.data" class="subset_item" :key="item.id"
                                :class="{ 'subset_selected': subsetSelectedId === item.id }"
                                @click="subsetChange(item.id)">{{ item.name }}</div>
                        </yk-scrollbar>
                    </template>
                </yk-popconfirm>

            </yk-space>
        </div>
        <div>
            <FilesItem v-if="count > 0" :filesData="files" class="files_main" @subsetIdChange="subsetIdChange" @fileDelete="fileDelete"
                @fileCheck="fileCheck" />
        </div>
        <div v-if="count > 0" class="pagination">
            <yk-pagination :total="count" size="m" @change="changePage"
                :default-page-size="props.pageSize"></yk-pagination>
        </div>
        <Empty v-if="files.length === 0" />
    </div>
</template>
<script setup lang="ts">
import { ref, onMounted, getCurrentInstance, watch } from 'vue';
// import { mkfiles, subset } from '../../mock/data';
import type { fileData } from '../../utils/interface';
import { getFileApi, deleteFileApi, removeFileApi } from '../../api/file_api';
import { useUserStore } from '../../stores/user';
import { useCode } from "../../hooks/codeHook";
import { useSubset } from "../../hooks/subsetHook";
import { useSubsetStore } from '../../stores/subset';
import FilesItem from './files-item.vue';
import Empty from '../common/empty.vue';
import './files.less';

const subsetStore = useSubsetStore();
const userStore = useUserStore();
const { tackleCode } = useCode();

const {
    rawSubset
} = useSubset(); // 获取分组列表

// 定义组件属性类型和默认值
type fileProps = {
    token?: string,
    pageSize: number,//每页多少条数据
    subsetId: number | string | null,//当前分组id
    nowPage?: number,//当前页码
    count?: boolean
}
const props = withDefaults(defineProps<fileProps>(), {
    pageSize: 8,
    nowSubset: { id: 0, type: 'all' },
    subsetId: null,
})

const proxy: any = getCurrentInstance()?.proxy

// 定义响应式数据
// 总数
const count = ref<number>(123)
// 数据内容
const files = ref<fileData[]>([]);
// 被选择图片的id数组
const checkedId = ref<number[]>([]);
// 全选
const checkedAll = ref(false);
// 半选
const indeterminate = ref(false);
// 分类选择
const subsetSelectedId = ref<number | string>();
//分类内容

// 请求类型定义
type Request = {
    token?: string,
    pageSize: number,//每页多少条数据
    nowPage: number,//当前页码
    subsetId: number | string,//当前分组id
    count?: boolean
}

// 请求对象
const request: Request = {
    token: userStore.token,
    pageSize: props.pageSize,
    nowPage: 1,
    subsetId: props.subsetId || -1,
    count: false
}

// 获取数据
const drwData = (e: boolean) => {
    request.count = e;
    getFileApi(request).then((res) => {
        if (tackleCode(res.data.code)) {
            let data = res.data.data;
            console.log(data);
            let filesList = data.result;
            count.value = data.count;
            // 加入选择项
            for (let i = 0; i < filesList.length; i++) {
                filesList[i].selected = false;
            }
            files.value = filesList;
        }
    })
}

// 翻页处理
const changePage = (page: number) => {
    request.nowPage = page;
    drwData(true);

}



// 头部操作 - 全选处理
const handleChangeAll = (value: boolean) => {
    indeterminate.value = false;
    checkedAll.value = value;
    // 同步所有文件的选中状态
    if (files.value) {
        files.value.forEach((file: fileData) => {
            file.selected = value;
        });

        // 更新选中ID数组
        checkedId.value = value
            ? files.value.map((file: fileData) => file.id)
            : [];
    }
}

// 取消选择
const uncheck = () => {
    checkedAll.value = false;
    indeterminate.value = false;
    if (files.value) {
        files.value.forEach((file: fileData) => {
            file.selected = false;
        });
        checkedId.value = []; // 清空选中ID数组
    }
}

// 图片的勾选
const fileCheck = (e: number) => {
    // 先找到当前操作的文件项并切换选中状态
    let fileItem = files.value.find((item: fileData) => item.id === e);  // find 方法会立即停止遍历并返回这个匹配的文件对象，而不是遍历整个数组。
    if (fileItem) {
        fileItem.selected = !fileItem.selected;
    }
    checkedId.value = files.value
        .filter((item: fileData) => item.selected)
        .map((item: fileData) => item.id);
    // 半选与全选
    if (checkedId.value.length === 0) {
        checkedAll.value = false;
        indeterminate.value = false;
    } else if (checkedId.value.length === files.value.length) {
        indeterminate.value = false;
        checkedAll.value = true;
    } else {
        checkedAll.value = false;
        indeterminate.value = true;
    }
}

// 批量删除
const filesDelete = () => {
    if (!files.value) return;
    //收集提交后端的数据
    let url: string[] = [];
    checkedId.value.forEach(item => {
        let file = files.value.find((file: fileData) => file.id === item);
        if (file) {
            url.push(file.url);
        }
    })
    let request = {
        token: userStore.token,
        fileUrl: url,
        fileId: checkedId.value.join(','),
    }
    console.log(request);
    deleteFileApi(request).then((res) => {
        if (tackleCode(res.data.code)) {
            const deleteCount = checkedId.value.length;
            // 过滤掉选中的文件
            files.value = files.value.filter((file: fileData) => !checkedId.value.includes(file.id));
            drwData(true);
            // 清空选中ID
            checkedId.value = [];
            // 重置全选和半选状态
            checkedAll.value = false;
            indeterminate.value = false;
            // 显示成功消息
            proxy.$message({
                type: 'success',
                message: `成功删除 ${deleteCount} 个文件`
            });
        }
    })


}

// 删除单张图片 (批量删除逻辑已同步更新)
const fileDelete = async (id: number, url: string) => {
    let request = {
        token: userStore.token,
        fileId: id,
        fileUrl: url
    }
    let result = await deleteFileApi(request);
    if (tackleCode(result.data.code)) {
        // 1. 从数据源中移除目标图片
        files.value = files.value.filter((file: fileData) => file.id !== id);
        // 2. 从选中ID数组中移除该ID（如果存在）
        checkedId.value = checkedId.value.filter(itemId => itemId !== id);
        const wasSelected = checkedId.value.includes(id);
        // 3. 重新计算全选/半选状态
        if (files.value.length === 0) {
            // 没有文件时重置状态
            checkedAll.value = false;
            indeterminate.value = false;
        } else if (wasSelected) {
            // 如果删除的是选中项，重新检查全选状态
            checkedAll.value = checkedId.value.length === files.value.length;
            indeterminate.value = checkedId.value.length > 0 && !checkedAll.value;
        }
        proxy.$message({
            type: 'success',
            message: `成功删除文件`
        });
        // 刷新数据
        drwData(true);

    }
}

// 切换分组
const subsetChange = (e: number) => {
    subsetSelectedId.value = e;
}

// 切换单张图片的分组
const subsetIdChange = async (e: { id: number, subsetId: number }) => {
    console.log(e)
    let request = {
        token: userStore.token,
        fileId: e.id,
        subsetId: e.subsetId,
    }
    const result = await removeFileApi(request);
    console.log(result);
    if (tackleCode(result.data.code)) {
        proxy.$message({
            type: 'success',
            message: `成功切换分组`
        });
    }
}

//批量切换分组
const subsetIdsChange = async () => {
    let request = {
        token: userStore.token,
        fileId: checkedId.value.join(','),
        subsetId: subsetSelectedId.value,
    }
    console.log(request);
    const result = await removeFileApi(request);
    console.log(result);
    if (tackleCode(result.data.code)) {
        proxy.$message({
            type: 'success',
            message: `成功切换分组`
        });
    }
}

// 弹窗取消回调
function cancel() {
    proxy.$message({ type: 'warning', message: '你点击了取消按钮' })
}

// 弹窗确认回调，批量切换分组
function confirm() {
    subsetIdsChange();
}
watch(
    props,
    () => {
        request.nowPage = 1;
        request.subsetId = props.subsetId || -1;
        drwData(true);
    },
)

// 组件挂载时获取数据
onMounted(() => {
    drwData(true);
    rawSubset(2);
})

</script>
<style scoped lang="less">
.files {
    background-color: @bg-color-l;
    border-radius: @radius-m ;
    width: 100%;
    padding: @space-xl;

    &_tool {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: @space-l;
        border-radius: @radius-m ;
        background-color: @bg-color-m;

        &-delete {
            width: 20px;
            height: 20px;
            color: @font-color-s;
            cursor: pointer;

            &:hover {
                color: @font-color-l;
            }
        }

        &-switch {
            width: 20px;
            height: 20px;
            color: @font-color-s;
            cursor: pointer;
        }
    }

    &_main {
        padding: 24px 0 32px 0;
        display: grid;
        grid-template-columns: repeat(auto-fill, 200px);
        row-gap: 32px;
        column-gap: 24px;
        justify-content: center;
    }

    .pagination {
        padding: @space-l 0 0 0;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        width: 100%;
    }
}
</style>